Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Solution:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  11. ListNode l = new ListNode(0);
  12. ListNode p = l;
  13. while (l1 != null || l2 != null) {
  14. if (l1 == null) {
  15. p.next = l2;
  16. break;
  17. }
  18. if (l2 == null) {
  19. p.next = l1;
  20. break;
  21. }
  22. if (l1.val < l2.val) {
  23. p.next = l1;
  24. l1 = l1.next;
  25. } else {
  26. p.next = l2;
  27. l2 = l2.next;
  28. }
  29. p = p.next;
  30. }
  31. return l.next;
  32. }
  33. }